/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.web.api;

import com.google.common.collect.Maps;
import com.guoyu.project.common.utils.IpAddressUtils;
import com.guoyu.project.common.utils.JsonUtil;
import com.guoyu.project.common.utils.SHA256Utils;
import com.guoyu.project.common.utils.TimeUtil;
import com.guoyu.project.common.web.APIResponse;
import com.guoyu.project.model.UserInfo;
import com.guoyu.project.model.enums.AccountType;
import com.guoyu.project.service.UserInfoService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author: libo Date: 17-6-22 Time: 上午11:19
 * @version: \$Id$
 */
@Controller
@RequestMapping("api")
public class LoginApiController extends BaseApiController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private UserInfoService userInfoService;

    @RequestMapping("register")
    @ResponseBody
    public APIResponse register(UserInfo userInfo) {

        try {
            userInfoService.register(userInfo.getUserName(), userInfo.getPhone(), userInfo.getEmail(),
                    userInfo.getPassword(), AccountType.NORM);
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
        logger.info("用户注册信息：{}", JsonUtil.encode(userInfo));
        return APIResponse.returnSuccess();
    }

    @RequestMapping("login")
    @ResponseBody
    public APIResponse login(String userName, String password, HttpServletRequest request) {
        UserInfo userInfo = userInfoService.queryByName(userName);
        if(userInfo == null){
            return APIResponse.returnFail("用户不存在");
        }
        // 登陆次数
        if(request.getSession().getAttribute(userName+"login_num") == null){
            request.getSession().setAttribute(userName+"login_num",1);
        }
        int userLoginNum = (Integer)request.getSession().getAttribute(userName + "login_num");
        if(userLoginNum > 6){
            request.getSession().removeAttribute(userName+"login_num");
            return APIResponse.returnFail("输入密码次数超过限制，请稍后再试");
        }
        request.getSession().setAttribute(userName+"login_num",userLoginNum+1);
        if (StringUtils.equals(userInfo.getPassword(), SHA256Utils.getSHA256String(password)) ||
                StringUtils.equals(userInfo.getPassword(), DigestUtils.md5Hex(password))) {
            setCurrentUser(request, userInfo);
            request.getSession().removeAttribute(userName+"login_num");
            logger.info("用户：{}登陆，登陆时间：{}，登陆ip：{}",userName, TimeUtil.getTimeFormat(), IpAddressUtils.getIpAddress(request));
            return APIResponse.returnSuccess(userInfo);
        } else{
            return APIResponse.returnFail("密码错误,你还有"+(6 - userLoginNum + "")+"次机会！");
        }
    }

    @RequestMapping("forgotPassword")
    @ResponseBody
    public APIResponse forgotPassword(String phone, String email, String password) {
        if (StringUtils.isBlank(password)) {
            return APIResponse.returnFail("密码不能为空");
        }

        Map<String, Object> params = Maps.newHashMap();
        params.put("phone", phone);
        params.put("email", email);
        UserInfo userInfo = userInfoService.querySingleUser(params);
        if (userInfo == null) {
            return APIResponse.returnFail("手机号为" + phone + ",邮箱为" + email + "的用户不存在");
        }

        userInfoService.modifyPassword(userInfo.getId(), password);
        return APIResponse.returnSuccess();
    }

    @RequestMapping("isLogin")
    @ResponseBody
    public APIResponse isLogin(HttpServletRequest request) {
        UserInfo userInfo = getCurrentUser(request);
        if (userInfo == null) {
            return APIResponse.returnSuccess(false);
        }
        return APIResponse.returnSuccess(userInfo.getAccountType());
    }

    @RequestMapping("logout")
    @ResponseBody
    public APIResponse logout(HttpSession session) {
        session.invalidate();
        return APIResponse.returnSuccess(true);
    }
}
